package sk.lukaskrupa.guess.the.color.ui;

import static sk.lukaskrupa.guess.the.color.core.ApplicationConstants.COLOR_REPETITION_STRING;
import static sk.lukaskrupa.guess.the.color.core.ApplicationConstants.DIFFICULTY_PREF_STRING;
import sk.lukaskrupa.guess.the.color.core.DifficultyEnum;
import sk.lukaskrupa.guess.the.color.listeners.SettingsButtonListener;
import sk.lukaskrupa.guess.the.color.logging.Logging;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.RadioGroup;

/**
 * Settins activity, where game could be setup.
 * 
 * @author Lukas Krupa (lukas0krupa@gmail.com)
 * 
 */
public class Settings extends Activity {

	private static final Logging logger = Logging.getLog(Settings.class);

	private SettingsButtonListener settingsListener;
	private SharedPreferences preferences;

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected void onStart() {
		super.onStart();

		logger.info("onStart", "Starting Settings activity.");
		setContentView(R.layout.settings);

		this.preferences = getSharedPreferences(getResources().getString(R.string.applicationData), Context.MODE_PRIVATE);

		this.settingsListener = new SettingsButtonListener(this);

		((Button) findViewById(R.id.saveSettings)).setOnClickListener(this.settingsListener);
		((Button) findViewById(R.id.backSettings)).setOnClickListener(this.settingsListener);

		// Setting settins according to save data.
		((RadioButton) findViewById(DifficultyEnum.getResourceIdForInternalValue(this.preferences.getInt(DIFFICULTY_PREF_STRING,
				DifficultyEnum.EASY.getValue())))).setChecked(true);
		((CheckBox) findViewById(R.id.colorRepetitionCHB)).setChecked(this.preferences.getBoolean(COLOR_REPETITION_STRING, false));

	}
	/**
	 * Save settings and exists settings activity.
	 */
	public void saveAndExit() {

		SharedPreferences.Editor appSettingsEditor = this.preferences.edit();

		int rbChecked = ((RadioGroup) findViewById(R.id.difficultiesRG)).getCheckedRadioButtonId();
		boolean colorRepetition = ((CheckBox) findViewById(R.id.colorRepetitionCHB)).isChecked();

		// Settings saving
		logger.debug("saveAndExit", "Saving new difficulty: " + DifficultyEnum.enumForResourceId(rbChecked));
		appSettingsEditor.putInt(DIFFICULTY_PREF_STRING, DifficultyEnum.enumForResourceId(rbChecked).getValue());
		appSettingsEditor.putBoolean(COLOR_REPETITION_STRING, colorRepetition);

		// Saving
		appSettingsEditor.apply();
		appSettingsEditor.commit();

		logger.info("saveAndExit", "Settings saved.");

		this.exit();
	}
	/**
	 * Exists settings activity, without saving.
	 */
	public void exit() {
		finish();
	}

}
